//
//  ITNetWorkManager.m
//  GLPFinance
//
//  Created by ITBE on 16/10/28.
//  Copyright © 2016年 intube. All rights reserved.
//

#import "ITNetWorkManager.h"
#import "ITLocationManager.h"
#import "ITGeneralManager.h"
//#import "SignSDK.h"

#define DefaultCachePolicy NSURLRequestReloadIgnoringLocalCacheData

#define UseSignSDK 0

static ITNetWorkManager *scNetWorkManager;
static NSArray *accountURI;
static NSOperationQueue *netWorkOperationQueue;

@implementation ITNetWorkManager
+(id)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (scNetWorkManager == nil) {
            scNetWorkManager = [[ITNetWorkManager alloc] init];
            accountURI = @[@"/login",@"/activation",@"/logout",@"/bind"];
            netWorkOperationQueue = [NSOperationQueue new];
            //[scNetWorkManager updateSession];
            scNetWorkManager.defaultSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:netWorkOperationQueue];
            
        }
    });
    return scNetWorkManager;
}

-(NSDictionary *) defaultHeader
{
    return [self defaultHeader:[ITUserManager token] time:[NSDate date] key:@""];
}

-(NSMutableDictionary*)defaultHeader:(NSString *)token time:(NSDate *)time key:(NSString *)key{
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    header[@"Content-Type"] = @"application/json";
    header[@"Authentication"] = token;
    header[@"User-Agent-Client"] = [[ITLocationManager shareManager] returnUserAgent];
    header[@"User-Agent-NetWork"] = [[ITLocationManager shareManager] returnNetWorkAgent];
    header[@"X-Skynet-Sign"] = [[ITLocationManager shareManager] returnSignString:time];
    header[@"User-Agent-Language"] = @"EN";
    return header;
}


- (void)handelWithError:(NSError *)error{
    //fix 303 error
    self.defaultSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:netWorkOperationQueue];
}

- (NSURLSessionDataTask *)request:(NSString *)uri method:(NSString *)method parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@%@",API_BASE,uri];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:DefaultCachePolicy timeoutInterval:TimeOut];
    request.HTTPMethod = method;
    // 2.设置请求头
    
    ITNetWorkModel *ret = ITNetWorkModel.new;
    ret.url = uri;
    ret.beginTime = CACurrentMediaTime();
    
    //NSString *secret = [SignSDK generateSecret];
    NSDate *now = [NSDate date];
    [request setAllHTTPHeaderFields:[self defaultHeader:ITUserManager.token time:now key:@""]];
    //[request setAllHTTPHeaderFields:self.defaultHeader];
    
    if (parameters && [parameters allKeys].count > 0) {
        if ([method isEqualToString:@"GET"]) {
            [url appendString:@"?"];
            for (NSString *key in [parameters allKeys]) {
                NSString *value = [parameters objectForKey:key];
                [url appendFormat:@"%@=%@",key,value];
                if (![key isEqualToString:[[parameters allKeys] lastObject]]) {
                    [url appendFormat:@"&"];
                }
            }
            request.URL = [NSURL URLWithString:url];
        }else {
            NSData *data = nil;
            {
                NSError *error = nil;
                data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
                request.HTTPBody = data;
                if (error != nil) {
                    NSLog(@"error = %@", error);
                }
            }
            request.HTTPBody = data;
        }
    }
    ret.params = parameters;
    ret.encodeTime = CACurrentMediaTime();
    // 4.发送请求
    WEAKSELF
    NSURLSession *session = _defaultSession;
    //NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:netWorkOperationQueue];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        ret.finishTime = CACurrentMediaTime();
        if (error) {
            ret.error = error;
            ret.message = error.localizedDescription;
            ret.decodeTime = CACurrentMediaTime();
            [weak_self handelWithError:error];
        }else{
            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
            NSInteger statusCode =  res.statusCode;
            ret.statusCode = statusCode;
            if (data) {
                id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if (obj[@"code"]) {
                    [ret modelSetWithJSON:obj];
                    ret.success = ret.code == 200;
                }else {
                    ret.data = obj;
                }
            }
            ret.decodeTime = CACurrentMediaTime();
        }
        if(callback)callback(ret);
    }];
    [task resume];
    return task;
}

- (NSURLSessionDataTask *)goRequest:(NSString *)uri method:(NSString *)method parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    GlobalDelay(0, ^{
        if (ITUserManager.currentMember == nil) {
            [ITUserManager.shareManager activeDevice:^(ITUserInfo * _Nonnull member) {
                if (member) {
                    [self request:uri method:method parameters:parameters callback:callback];
                }else{
                    if (callback) callback(nil);
                }
            }];
        }else {
            [self request:uri method:method parameters:parameters callback:callback];
        }
    });
    return nil;
}

- (NSURLSessionDataTask *)post:(NSString *)uri parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    return [self goRequest:uri method:@"POST" parameters:parameters callback:callback];
}

- (NSURLSessionDataTask *)get:(NSString *)uri parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    return [self goRequest:uri method:@"GET" parameters:parameters callback:callback];
}


- (NSURLSessionDataTask *)put:(NSString *)uri parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    return [self goRequest:uri method:@"PUT" parameters:parameters callback:callback];
}

- (NSURLSessionDataTask *)doDelete:(NSString *)uri parameters:(id)parameters callback:(ApiSuccessCallback)callback{
    return [self goRequest:uri method:@"DELETE" parameters:parameters callback:callback];
}


- (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURI
                     savedPath:(NSString*)savedPath
               downloadSuccess:(ApiSuccessCallback)success
               downloadFailure:(ApiFailedCallback)failure
                      progress:(ApiDownloadFileProgress)progress
{
    NSString *url = requestURI;
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"progress = %f", (float)downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
}


-(void)uploadImage:(UIImage *)image uri:(NSString *)uri parameters:(id)parameters  success:(ApiSuccessCallback)success failed:(ApiFailedCallback)failed
{
    NSString *url = [NSString stringWithFormat:@"%@%@",API_BASE,uri];
    AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];
    [requestManager.requestSerializer setTimeoutInterval:TimeOut];
    [requestManager.requestSerializer setValue:[ITUserManager token] forHTTPHeaderField:@"Authentication"];
    [requestManager POST:url parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        UIImage *fixImage = [image fixOrientation];
        NSData *imageData = UIImagePNGRepresentation(fixImage);
        if (imageData == nil) {
            imageData = UIImageJPEGRepresentation(image, 1.0f);
        }
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"head.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        ITNetWorkModel *ret = [ITNetWorkModel modelWithJSON:responseObject];
        ret.statusCode = response.statusCode;
        success(ret);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed(error);
    }];
}
@end
